package com.ip.db.config;


import com.ip.db.constant.DataSourceEnum;

public class DataSourceContextHolder {

    private static final ThreadLocal contextHolder = new ThreadLocal<>();

    /**
     * 设置数据源
     *
     * @param dataSourceEnum
     */
    public static void setDataSource(DataSourceEnum dataSourceEnum) {
        contextHolder.set(dataSourceEnum.getCode());
    }

    /**
     * 取得当前数据源
     *
     * @return String
     */
    public static String getDataSource() {
        String result = DataSourceEnum.dataSourceWirte.getCode();
        if(contextHolder.get() != null){
            result = contextHolder.get().toString();
        }
        return result;
    }

    /**
     * 清除上下文数据
     */
    public static void clearDataSource() {
        contextHolder.remove();
    }

    /**
     * 根据APP_KEY设置数据源
     * @param app_key
     */
    public static void setDataSource(String app_key){
        DataSourceEnum dataSourceEnum = DataSourceEnum.get(app_key);
        contextHolder.set(dataSourceEnum.getCode());
    }
}
